//The MIT License
//
//Copyright (c) 2009 nodchip
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
package tv.dyndns.kishibe.client.game;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import tv.dyndns.kishibe.client.Constant;
import tv.dyndns.kishibe.client.Controller;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class WidgetInputTyping extends WidgetInputBase implements ClickHandler {
	public static final int TYPING_HIRA = 0;
	public static final int TYPING_KATA = 1;
	public static final int TYPING_ALPHA = 2;
	private WidgetAnswer labelAnswer;
	private static final String BUTTON_LETTER[] = { "あかさたなはまやらわぁゃいきしちにひみ り ぃゅうくすつぬふむゆるをぅょえけせてねへめ れ ぇっおこそとのほもよろんぉー", "アカサタナハマヤラワァャイキシチニヒミ リ ィュウクスツヌフムユルヲゥョエケセテネヘメ レ ェッオコソトノホモヨロンォー", "１２３４５６７８９０ＡＢＣＤＥＦＧＨＩＪＫＬＭＮＯＰＱＲＳＴＵＶＷＸＹＺ" };
	private static final int[] NUMBER_OF_LETTERS_PER_ROW = { 12, 12, 10 };
	private static final String DAKUTEN_FROM = "かきくけこさしすせそたちつてとはひふへほがぎぐげござじずぜぞだぢづでどばびぶべぼっカキクケコサシスセソタチツテトハヒフヘホガギグゲゴザジズゼゾダヂヅデドバビブベボッっぱぴぷぺぽパピプペポウヴ";
	private static final String DAKUTEN_TO = "がぎぐげござじずぜぞだぢづでどばびぶべぼかきくけこさしすせそたちつてとはひふへほづガギグゲゴザジズゼゾダヂヅデドバビブベボカキクケコサシスセソタチツテトハヒフヘホヅづばびぶべぼバビブベボヴウ";
	private static final String HANDAKUTEN_FROM = "はひふへほぱぴぷぺぽハヒフヘホパピプペポばびぶべぼバビブベボ";
	private static final String HANDAKUTEN_TO = "ぱぴぷぺぽはひふへほパピプペポハヒフヘホぱぴぷぺぽパピプペポ";
	private static final List<Map<String, String>> dictionary = createDictionary();
	private static final int DICTIONARY_DAKUTEN = 0;
	private static final int DICTIONARY_HANDAKUTEN = 1;
	private static final int SIZE_OF_DICTIONARY = 2;

	private static List<Map<String, String>> createDictionary() {
		final List<Map<String, String>> map = new ArrayList<Map<String, String>>();
		for (int i = 0; i < SIZE_OF_DICTIONARY; ++i) {
			map.add(new HashMap<String, String>());
		}

		for (int i = 0; i < DAKUTEN_FROM.length(); ++i) {
			map.get(DICTIONARY_DAKUTEN).put(DAKUTEN_FROM.substring(i, i + 1), DAKUTEN_TO.substring(i, i + 1));
		}

		for (int i = 0; i < HANDAKUTEN_FROM.length(); ++i) {
			map.get(DICTIONARY_HANDAKUTEN).put(HANDAKUTEN_FROM.substring(i, i + 1), HANDAKUTEN_TO.substring(i, i + 1));
		}

		return map;
	}

	private final Grid gridLetter;
	private ButtonLetter[] buttons;
	// 消す・濁点・半濁点・OK
	private final Button buttonDakuten = new Button("゛", this);
	private final Button buttonHandakuten = new Button("゜", this);
	private final Button buttonDelete = new Button("消す", this);
	private final Button buttonOK = new Button("ＯＫ", this);
	private final VerticalPanel panel = new VerticalPanel();

	public WidgetInputTyping(WidgetAnswer widgetAnswer, String answer) {
		labelAnswer = widgetAnswer;

		final int letterType = judgeLetterType(answer);
		if (letterType == -1) {
			gridLetter = null;
			return;
		}
		final String letters = BUTTON_LETTER[letterType];

		final int numberOfLettersPerRow = NUMBER_OF_LETTERS_PER_ROW[letterType];
		gridLetter = new Grid(5, numberOfLettersPerRow + 1);

		buttons = new ButtonLetter[numberOfLettersPerRow * 5];

		for (int row = 0; row < 5; ++row) {
			for (int column = 0; column < numberOfLettersPerRow; ++column) {
				final int index = row * numberOfLettersPerRow + column;

				if (letters.length() <= index) {
					break;
				}

				final String letter = letters.substring(index, index + 1);

				if (letter.equals(" ")) {
					continue;
				}

				final ButtonLetter buttonLetter = new ButtonLetter(letter, widgetAnswer);
				buttons[index] = buttonLetter;
				gridLetter.setWidget(row, column, buttonLetter);
			}
		}

		buttonDakuten.setStyleName("gwt-Button-typing");
		buttonHandakuten.setStyleName("gwt-Button-typing");
		buttonDelete.setStyleName("gwt-Button-typingControl");
		buttonOK.setStyleName("gwt-Button-typingControl");

		buttonDelete.setWidth("90px");
		buttonOK.setWidth("90px");

		final int mostLeftColumIndex = gridLetter.getColumnCount() - 1;
		if (letterType == TYPING_HIRA || letterType == TYPING_KATA) {
			gridLetter.setWidget(0, mostLeftColumIndex, buttonDakuten);
			gridLetter.setWidget(1, mostLeftColumIndex, buttonHandakuten);
		}
		gridLetter.setWidget(3, mostLeftColumIndex, buttonDelete);
		gridLetter.setWidget(4, mostLeftColumIndex, buttonOK);

		panel.add(gridLetter);

		add(panel);
		add(new HTML("ボタンを押して答えを入力してください<br/>最後にOKを押してください"));
	}

	private final static String VALID_LETTER[] = { "あかさたなはまやらわいきしちにひみりをうくすつぬふむゆるんえけせてねへめれおこそとのほもよろーがぎぐげござじずぜぞだぢづでどばびぶべぼぱぴぷぺぽぁぃぅぇぉゃゅょっ", "アカサタナハマヤラワイキシチニヒミリヲウクスツヌフムユルンエケセテネヘメレオコソトノホモヨローガギグゲゴザジズゼゾダヂヅデドバビブベボパピプペポァィゥェォャュョッヴ", "１２３４５６７８９０ＡＢＣＤＥＦＧＨＩＪＫＬＭＮＯＰＱＲＳＴＵＶＷＸＹＺ" };

	private int judgeLetterType(String answer) {
		final char c = answer.charAt(0);

		for (int type = 0; type < VALID_LETTER.length; ++type) {
			if (VALID_LETTER[type].indexOf(c) != -1) {
				return type;
			}
		}

		Controller.getInstance().showErrorMessage("入力ウィジットが文字判定に失敗しました");

		return -1;
	}

	public void enable(boolean enabled) {
		for (int i = 0; i < buttons.length; ++i) {
			final Button button = buttons[i];
			if (button != null) {
				button.setEnabled(enabled);
			}
		}

		buttonDakuten.setEnabled(enabled);
		buttonHandakuten.setEnabled(enabled);
		buttonDelete.setEnabled(enabled);
		buttonOK.setEnabled(enabled);
	}

	@Override
	public void onClick(ClickEvent event) {
		final Widget sender = (Widget) event.getSource();
		if (sender == buttonDakuten) {
			// 濁点ボタン
			playSound(Constant.SOUND_URL_BUTTON_PUSH);
			final String lastLetter = dictionary.get(DICTIONARY_DAKUTEN).get(labelAnswer.getLastLetter());
			if (lastLetter != null) {
				labelAnswer.setLastLetter(lastLetter);
			}

		} else if (sender == buttonHandakuten) {
			// 半濁点ボタン
			playSound(Constant.SOUND_URL_BUTTON_PUSH);
			final String lastLetter = dictionary.get(DICTIONARY_HANDAKUTEN).get(labelAnswer.getLastLetter());
			if (lastLetter != null) {
				labelAnswer.setLastLetter(lastLetter);
			}

		} else if (sender == buttonDelete) {
			// 消すボタン
			labelAnswer.removeLetter();

		} else if (sender == buttonOK) {
			// OKボタン
			enable(false);
			sendAnswer(labelAnswer.getText());

		}
	}
}
